
package edu.zqu.collegeField.common.exception;


import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import edu.zqu.common.core.text.Convert;
import edu.zqu.common.result.ZQUResult;
import org.springframework.dao.DataAccessException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 廖森
 * @Date 2020/6/28/004.
 */
@RestControllerAdvice(basePackages = "edu.zqu.collegeField.project.controller")
public class GlobalExceptionHandler {


    //校验异常
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ZQUResult MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        Map<String, String> map = e.getBindingResult().getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        ZQUResult result = ZQUResult.error(map.values().toString());
        return result;
    }

    //参数异常
    @ResponseBody
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ZQUResult IllegalArgumentException(Exception e) {
        ZQUResult result = ZQUResult.error(e.getMessage());
        return result;
    }

    //MybatisPlus操作异常
    @ResponseBody
    @ExceptionHandler(value = MybatisPlusException.class)
    public ZQUResult MybatisPlusException(Exception e) {
        ZQUResult result = ZQUResult.error(e.getMessage());
        return result;
    }

    //自定义异常
    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public ZQUResult MyException(Exception e) {
        System.out.println("2");
        ZQUResult result = ZQUResult.error(e.getMessage());
        return result;
    }

    //处理空指针的异常
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ZQUResult handleNullPointerException(NullPointerException e) {
        return ZQUResult.error(e.getMessage());
    }

    // 捕获所有逃逸的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ZQUResult handleAllUnCatchException(Exception e) {
        return ZQUResult.error(e.getMessage());
    }

    // 捕获sql的异常
    @ExceptionHandler(DataAccessException.class)
    @ResponseBody
    public ZQUResult handleDataAccessException(DataAccessException e) {
        if(e.getCause().getMessage().endsWith("doesn't have a default value"))
            return ZQUResult.error("部分字段不能为空！");
        return ZQUResult.error(Convert.toStr(e.getCause().getMessage()));
    }

}
